package hcmute.pps;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	Button bt;
	TextView tv;
	String TAG = "AAA";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		bt = (Button) findViewById(R.id.btGetLocation);
		bt.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				LocationManager locationManager;
				String context = Context.LOCATION_SERVICE;
				locationManager = (LocationManager) getSystemService(context);
				String provider = LocationManager.GPS_PROVIDER;
				Location location = locationManager
						.getLastKnownLocation(provider);

				String latLongString;
				if (location != null) {
					double lat = location.getLatitude();
					double lng = location.getLongitude();
					latLongString = "Lat:" + lat + "\nLong:" + lng;
				} else {
					latLongString = "No location found";
				}
				tv.setText("Your Current Position is:\n" + latLongString);

				List<Address> addresses;

				try {
					Geocoder mGC = new Geocoder(getApplicationContext(), Locale
							.getDefault());

					addresses = mGC.getFromLocation(location.getLatitude(),
							location.getLongitude(), 1);
					if (addresses != null) {
						Address currentAddr = addresses.get(0);
						StringBuilder mSB = new StringBuilder("Address:\n");
						for (int i = 0; i < currentAddr
								.getMaxAddressLineIndex(); i++) {
							mSB.append(currentAddr.getAddressLine(i)).append(
									"\n");
						}
						tv.setText(mSB.toString());
					}
				} catch (IOException e) {
					tv.setText(e.getMessage());
				}

			}

		});
		tv = (TextView) findViewById(R.id.tvShowResult);

	}
}